package com.lsx.logisticscore.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lsx.logisticscore.entity.Car;
import com.lsx.logisticscore.entity.Employee;
import com.lsx.logisticscore.mapper.CarMapper;
import com.lsx.logisticscore.mapper.EmployeeMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class CarService {
    @Autowired
    private CarMapper carMapper;

    @Autowired
    private EmployeeService employeeService;
    public int insertCar(Car car){
        //要做判断 manager必须是存在且类型为司机
        Employee manager =  employeeService.getEmployeeById(car.getManagerId());
//        log.info("$$$$$$$$ 查出的employee为： {}", manager);
        if (manager == null){
            //员工不存在错误
            return -1;
        }else if (!"司机".equals(manager.getType())){
            //员工类型错误
            return -2;
        }
        car.setManagerName(manager.getName());
        car.setEntryDate(new Date());
        car.setState("free");
        carMapper.insertSelective(car);
        Integer id = car.getCarId();
        return id;
    }

    public Page<Car> listCar(Page<Car> page, String type){
        QueryWrapper<Car> wrapper = new QueryWrapper<>();
        wrapper.eq("car_type", type);
        return carMapper.selectPage(page, wrapper);
    }


    public String updateCar(Car car){
        //在此进行外键约束的判断 确保manager是存在的且是司机
        Employee employee = employeeService.getEmployeeById(car.getManagerId());
        if (employee == null){
            //员工不存在错误
            return "-1";
        }else if (!"司机".equals(employee.getType())){
            //员工类型错误
            return "-2";
        }
        car.setManagerName(employee.getName());
        carMapper.updateByPrimaryKeySelective(car);
        return employee.getName();
    }
}
